package com.csdj.rest.inteceptor;

import com.csdj.common.WebResult;
import com.csdj.common.constant.CommonConstant;
import com.csdj.common.constant.RedisConstant;
import com.csdj.common.constant.WebResultConstant;
import com.csdj.middleware.RedisService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginInteceptor implements HandlerInterceptor {

    Logger log = LoggerFactory.getLogger("LoginInterceptor");

    //拦截器是否要生效
    private boolean isInvalid;

    private RedisService redisService;

    public void setInvalid(boolean invalid) {
        isInvalid = invalid;
    }

    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    public LoginInteceptor(RedisService redisService){
        this.redisService = redisService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(isInvalid){
//            log.info(handler.toString());
//            log.info(request.getRequestURI());
            //从请求头信息中拿userid
            String userId = request.getHeader(CommonConstant.HEADER_USER_ID);
            if(StringUtils.hasText(userId)) {
                //从请求头信息拿token
                String token = request.getHeader(CommonConstant.HEADER_TOKEN);
                if(StringUtils.hasText(token)){
                    //从缓存中取token
                    String cacheToken = redisService.getString(RedisConstant.TOKEN_PREFIX+userId);
                    if(StringUtils.hasText(cacheToken)){
                        if(cacheToken.equals(token)){
                            return true;
                        }
                    }
                }
            }
            final PrintWriter writer = response.getWriter();
            final ObjectMapper mapper = new ObjectMapper();
            final String resp = mapper.writeValueAsString(new WebResult(WebResultConstant.NO_LOGIN));
            log.error("url:{} code:401",request.getRequestURL());
            writer.write(resp);
            writer.close();
            return false;
        }else{
            //拦截器不生效
            return true;
        }
    }

}
